package org.example.util;

import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

/**
 * @author Donald
 * @create 2020-04-18 22:11
 */
public class DynamicDatasourceContextHolder {
    private static final ThreadLocal<String> contextHolder =  new ThreadLocal<String>(){
        /**
         * 设置默认数据源
         * @return
         */
        @Override
        protected String initialValue() {
            return "master";
        }
    };

    public static List<Object> datasourceKeys = new LinkedList<>();

    /**
     * 设置数据源
     * @param key
     */
    public static void setDatasourceKey(String key){
        contextHolder.set(key);
    }

    /**
     * 获取数据源
     * @param key
     * @return
     */
    public static String getDatasource(){
        return contextHolder.get();
    }

    /**
     * 重置数据源
     */
    public static void clearDataSourceKey() {
        contextHolder.remove();
    }

    /**
     * 判断是否包含数据源
     * @param key 数据源key
     * @return
     */
    public static boolean containDataSourceKey(String key) {
        return datasourceKeys.contains(key);
    }

    /**
     * 添加数据源keys
     * @param keys
     * @return
     */
    public static boolean addDataSourceKeys(Collection<? extends Object> keys) {
        return datasourceKeys.addAll(keys);
    }

    public static String getDatasourceKey(){
        return  contextHolder.get();
    }
}
